package com.situ.blog.dao.impl;


import com.situ.blog.dao.IBlogDao;
import com.situ.blog.pojo.entity.Blog;
import com.situ.blog.pojo.query.BlogQuery;
import com.situ.blog.util.JDBCUtils;
import com.situ.blog.util.JDBCUtils2;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BlogDaoImpl implements IBlogDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Blog> selectByPage(BlogQuery blogQuery) {
        String sql = "select * from blog where 1=1";
        //构造一个集合存放所有的条件
        List<Object> queryList = new ArrayList<>();
        String queryName = blogQuery.getName();
        if (queryName != null && !queryName.equals("")) {
            sql += " and name like ?";
            queryList.add("%" + queryName + "%");
        }
        sql += " limit ?,?";
        int offset = (blogQuery.getPage() - 1) * blogQuery.getLimit();
        queryList.add(offset);
        queryList.add(blogQuery.getLimit());
        List<Blog> list = template.query(sql,
                new BeanPropertyRowMapper<>(Blog.class), queryList.toArray());
        return list;
    }

    @Override
    public int selectTotalCount(BlogQuery blogQuery) {
        String sql = "select count(*) from blog where 1=1";
        //构造一个集合存放所有的条件
        List<Object> queryList = new ArrayList<>();
        String queryName = blogQuery.getName();
        if (queryName != null && !queryName.equals("")) {
            sql += " and name like ?";
            queryList.add("%" + queryName + "%");
        }
//        Integer count = template.queryForObject(sql, Integer.class, queryList);
//        return count;
        return template.queryForObject(sql, Integer.class, queryList.toArray());
    }

    @Override
    public void deleteById(int id) {
        template.update("delete from blog where id=?", id);
    }

    @Override
    public void add(Blog blog) {
        template.update("insert into blog(name,content,image) values(?,?,?)",
                blog.getName(), blog.getContent(), blog.getImage());
    }

    @Override
    public Blog selectById(int id) {
        return template.queryForObject("select * from blog where id=?",
                new BeanPropertyRowMapper<>(Blog.class), id);
        /*return template.queryForObject("select * from blog where id=?",
                Blog.class, id);*/
    }

    @Override
    public void update(Blog blog) {
        template.update("update blog set name=?,content=? where id=?",
                blog.getName(), blog.getContent(), blog.getId());
    }
}
